package dp2.tablet.proyecto;




//import java.sql.Time;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.ExecutionException;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import dp2.tablet.proyecto.bean.EntradaBean;
import dp2.tablet.proyecto.bean.EventoBean;
import dp2.tablet.proyecto.bean.HorarioBean;
import dp2.tablet.proyecto.bean.ManejadorEntradas;
import dp2.tablet.proyecto.bean.PromocionBean;
import dp2.tablet.proyecto.bean.VentaBean;
import dp2.tablet.proyecto.bean.ZonaBean;
import dp2.tablet.proyecto.util.ImageDownloader;
import dp2.tablet.proyecto.util.JSONReader;
import dp2.tablet.proyecto.util.JSONReaderInt;
import dp2.tablet.proyecto.util.JSONReaderIntListener;
import dp2.tablet.proyecto.util.JSONReaderListener;
import dp2.tablet.proyecto.util.JSONReaderObject;
import dp2.tablet.proyecto.util.JSONReaderObjectListener;
import dp2.tablet.proyecto.util.JSONUbicaciones;
import dp2.tablet.proyecto.util.JSONUbicacionesListener;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.app.TabActivity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CalendarView;
import android.widget.CalendarView.OnDateChangeListener;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TableRow.LayoutParams;
import android.widget.TextView;
import android.widget.Toast;


public class Venta extends Activity implements OnDateChangeListener,OnClickListener,OnItemSelectedListener,JSONReaderListener,JSONReaderObjectListener,JSONUbicacionesListener,JSONReaderIntListener{
	TableLayout tbllDetalle;
	EventoBean objEvento;
	List<EntradaBean> lstEntrada;
	VentaBean venta;
	
	List<HorarioBean> lstHorarios=new ArrayList<HorarioBean>();
	List<ZonaBean> lstZonas=new ArrayList<ZonaBean>();
	List<PromocionBean> lstPromociones= new ArrayList<PromocionBean>();
	
	Button btnPreviousButtonCalendar=null;
	
	int intAsientosDisponibles=-1;	
	
	private Venta me=this;
	
	private Date dteCurrent;
	
	private RelativeLayout container;
	private int currentX;
	private int currentY;
	
	
	private static final String tag = "SimpleCalendarViewActivity";

	private ImageView calendarToJournalButton;
	private Button selectedDayMonthYearButton;
	private Button currentMonth;
	private ImageView prevMonth;
	private ImageView nextMonth;
	private GridView calendarView;
	private GridCellAdapter adapter;
	private Calendar _calendar;
	private int month, year;
	private final DateFormat dateFormatter = new DateFormat();
	private static final String dateTemplate = "MMMM yyyy";
	
	
	ProgressDialog myProgressDialog = null;
	int intContadorProgress=0;
	
	
	ImageDownloader imgDownloader;
	Drawable imagenZonas;
	
    /** Called when the activity is first created. */
	public void refresh(){
		if (isNetworkAvailable()==true){
        //Aca estoy poniendi la clase venta 
		
			if (verificarCajaAbierta()){
				//if (objEvento.getIdEvento()!=((Principal)this.getParent()).getEvento().getIdEvento()){
					
					cargarElementosEvento();
					
					
				//}	
		        
				ManejadorEntradas manejador = ManejadorEntradas.getInstance();
		        manejador.setVenta(venta);
				
		        loadTableLayout();
			}
			else{			
				final Dialog dialog = new Dialog(this);
				dialog.setContentView(R.layout.dialog2);
				dialog.setTitle("Fin de sesion");
				
				TextView text = (TextView) dialog.findViewById(R.id.text2);
				text.setText("Se ha cerrado la caja, no puede continuar con las operaciones");
				Button dialogButton = (Button) dialog.findViewById(R.id.dialogButtonOK2); 
				dialogButton.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						
						((Principal)me.getParent()).finish();
				    	Principal.abriCaja.finish();
				    	/*
						Intent intent= new Intent();
						intent.setClass(getParent(), Login.class);
			    		startActivity(intent);
			    		*/
					}
				});			
				dialog.show();
			}		
		}else{
			Toast.makeText(this,"Problema de conexion", Toast.LENGTH_SHORT).show();
		}
		
	}
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.venta);
        
        Spinner cboZona= (Spinner) findViewById(R.id.VentaCboZona);
        cboZona.setOnItemSelectedListener(this); 
        
        Spinner cboHorario= (Spinner) findViewById(R.id.VentaCboHorario);
        cboHorario.setOnItemSelectedListener(this); 
        
        Spinner cboPromocion= (Spinner) findViewById(R.id.VentaCboPromocion);
        cboPromocion.setOnItemSelectedListener(this); 
        
        imgDownloader=new ImageDownloader();
                
        tbllDetalle = (TableLayout) findViewById(R.id.PagosTbllDetalle);
                
        //Calendario        
        _calendar = Calendar.getInstance(Locale.getDefault());
		month = _calendar.get(Calendar.MONTH) + 1;
		year = _calendar.get(Calendar.YEAR);

		prevMonth = (ImageView) this.findViewById(R.id.prevMonth);
		prevMonth.setOnClickListener(this);

		currentMonth = (Button) this.findViewById(R.id.currentMonth);
		currentMonth.setText(dateFormatter.format(dateTemplate, _calendar.getTime()));

		nextMonth = (ImageView) this.findViewById(R.id.nextMonth);
		nextMonth.setOnClickListener(this);

		calendarView = (GridView) this.findViewById(R.id.calendar);

		// Initialised
		//adapter = new GridCellAdapter(getApplicationContext(), R.id.calendar_day_gridcell, month, year);
		//adapter.notifyDataSetChanged();
		//calendarView.setAdapter(adapter);
        //*Calendario
		
		//dteCurrent=new Date();
		cargarElementosEvento();
        
        
    } 
    public void cargarElementosEvento(){
    	
        venta=((Principal)this.getParent()).getVenta();
        venta.setEstado(1);
        lstEntrada=venta.getEntradas();
        
    	objEvento=((Principal)this.getParent()).getEvento();
    	
    	llenarHorarios();
    	
    	_calendar = Calendar.getInstance(Locale.getDefault());
		month = _calendar.get(Calendar.MONTH) + 1;
		year = _calendar.get(Calendar.YEAR);
    	setGridCellAdapterToDate(month, year);
    	
    	
        TextView txtEvento=(TextView) findViewById(R.id.VentaLblEvento);
        txtEvento.setText(objEvento.getStrNombre());
        TextView txtDescripcion=(TextView) findViewById(R.id.VentaLblDescripcion);
        txtDescripcion.setText(objEvento.getStrDescripcion());
        TextView txtDireccion=(TextView) findViewById(R.id.VentaLblDireccion);
        txtDireccion.setText("Direccion: "+((objEvento.getLugarEvento()==null)?"No registrada":objEvento.getLugarEvento()));
        TextView txtPeriodo=(TextView) findViewById(R.id.VentaLblPeriodo);
        
        SimpleDateFormat format= new SimpleDateFormat("dd/MM/yyyy");
        //txtPeriodo.setText("Período: Del "+format.format(objEvento.getDteFechaInici())+" al "+format.format(objEvento.getDteFechaFinVenta()));
        txtPeriodo.setText(objEvento.getFechaEvento());
        
        //cargarMapaZonas();        
        
        llenarZonas();
        llenarPromociones();
        
      //Llenado de datos del eventos
    	ImageView imgEvento= (ImageView) findViewById(R.id.ventaImgEvento);
    	
    	imgDownloader.download(objEvento.getUrlImagen(),imgEvento);
        
    }
    
    public void cargarZonas(){    	
    	if (isNetworkAvailable()==true){
	    	TableLayout tbllUbicaciones = (TableLayout) findViewById(R.id.VentaTblUbicaciones);
	        tbllUbicaciones.removeAllViews();
	        
	    	JSONObject jUrlZonas;
	    	try {
				JSONReaderObject reader = new JSONReaderObject();
				reader.setJSONReaderObjectListener((JSONReaderObjectListener)this);			
				jUrlZonas=(reader.execute("http://200.16.7.112:3000/event_management/events/dameMapaEvento/"+objEvento.getIdEvento()+".json")).get();
			} catch (InterruptedException e1) {
				e1.printStackTrace();
				return;
			} catch (ExecutionException e1) {
				e1.printStackTrace();
				return;
			}		
	    	ImageView ImgEvento= (ImageView) findViewById(R.id.VentaImgEvento);
	    	try {
				imgDownloader.download("http://200.16.7.112:3000"+jUrlZonas.getString("mapa_zona"),ImgEvento);
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}  
    	}else{
    		Toast.makeText(this,"Problema de conexion", Toast.LENGTH_SHORT).show();
    	}
    }
    /*
    public void cargarZonas(){
    	
    	
    	
    	ImageView ImgEvento= (ImageView) findViewById(R.id.VentaImgEvento);
    	ImgEvento.setBackgroundDrawable(imagenZonas);    	
    }
    */
    
    
    public void cargarUbicaciones(){    
    	
    	if (isNetworkAvailable()==true){
	    	
    		JSONUbicaciones reader = new JSONUbicaciones();
			reader.setJSONUbicacionesListener((JSONUbicacionesListener)this);
			try {
				intAsientosDisponibles=(reader.execute(""+((HorarioBean)((Spinner)(findViewById(R.id.VentaCboHorario))).getSelectedItem()).getIntId(),""+((ZonaBean)(((Spinner)findViewById(R.id.VentaCboZona)).getSelectedItem())).getIntId())).get();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ExecutionException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			if (intAsientosDisponibles!=-1){
				TextView txtAsiento=(TextView) findViewById(R.id.VentaTxtAsiento);
		    	txtAsiento.setText("-");
			}
	    	/*    	
	    	ImageView ImgEvento= (ImageView) findViewById(R.id.VentaImgEvento);
	        ImgEvento.setBackgroundDrawable(null);
	        
	        TableLayout tbllUbicaciones = (TableLayout) findViewById(R.id.VentaTblUbicaciones);
	        tbllUbicaciones.removeAllViews();
	        
	        for (int i=0,cont=0;i<50;i++){
	        	TableRow tblrDetallePago = new TableRow(this);
	        	tblrDetallePago.setLayoutParams(new LayoutParams(android.view.ViewGroup.LayoutParams.WRAP_CONTENT,android.view.ViewGroup.LayoutParams.WRAP_CONTENT));
	        	for (int j=0;j<50;j++,cont++){
	        		
	        		TextView btnUbi=new TextView(this);
	
	    			btnUbi.setText(""+cont);
	    			btnUbi.setBackgroundColor(Color.parseColor("#c5ced9"));
	    			
	    			LayoutParams lytAux= new LayoutParams(50,40);
	    			lytAux.setMargins(0, 1, 1, 0);
	    			btnUbi.setLayoutParams(lytAux);
	    			btnUbi.setGravity(Gravity.CENTER);
	    			
	    			btnUbi.setOnClickListener(this);    			
	    			tblrDetallePago.addView(btnUbi);  			
	        	}
	        	tbllUbicaciones.addView(tblrDetallePago);
			}        
	        */
			
    	}    	
    	else {
    		Toast.makeText(this,"Problema de conexion", Toast.LENGTH_SHORT).show();
		}
    }
    public boolean verificarCajaAbierta(){
    	if (isNetworkAvailable()==true){
	    	int intJSONEstadoCaja;
	    	try {
				JSONReaderInt reader = new JSONReaderInt();
				reader.setJSONReaderIntListener((JSONReaderIntListener)this);
				intJSONEstadoCaja=(reader.execute("http://200.16.7.112:3000/sales_management/sales_points/dameEstadoCaja/"+abrircaja.getCaja().getId()+".json")).get();
			} catch (InterruptedException e1) {
				e1.printStackTrace();
				return false;
			} catch (ExecutionException e1) {
				e1.printStackTrace();
				return false;
			}		
	    	if ((intJSONEstadoCaja==2)||(intJSONEstadoCaja==4)){
	    		return false;    		
	    	}
	    	else    	
	    		return true;    	
    	}else{
    		Toast.makeText(this,"Problema de conexion", Toast.LENGTH_SHORT).show();
    		return true;
    	}
    }    
    public void llenarPromociones(){
    	if (isNetworkAvailable()==true){
	    	JSONArray jPromociones;
			try {
				JSONReader reader = new JSONReader();
				reader.setJSONReaderListener((JSONReaderListener)this);
				//jPromociones=(reader.execute("http://200.16.7.112:3000/sales_management/sales_points/damePromocionesEvento/14.json")).get();
				jPromociones=(reader.execute("http://200.16.7.112:3000/sales_management/sales_points/damePromocionesEvento/"+objEvento.getIdEvento()+".json")).get();
			} catch (InterruptedException e1) {
				e1.printStackTrace();
				return;
			} catch (ExecutionException e1) {
				e1.printStackTrace();
				return;
			}		
			if (jPromociones!=null){    
				lstPromociones.clear();
				for(int i=0;i<jPromociones.length();i++){
					PromocionBean objPromocion= new PromocionBean();
					try {
						objPromocion.setIntId(jPromociones.getJSONObject(i).getInt("promotion_id"));
						objPromocion.setStrDescripcion(jPromociones.getJSONObject(i).getString("descripcion"));					
						
						SimpleDateFormat formatoDelTexto=new SimpleDateFormat("yyyy-MM-dd");
	
						String strFecha = jPromociones.getJSONObject(i).getString("start_date");					
						objPromocion.setDteFechaInicio(formatoDelTexto.parse(strFecha));
						
						strFecha = jPromociones.getJSONObject(i).getString("end_date");					
						objPromocion.setDteFechaFin(formatoDelTexto.parse(strFecha));
						
						strFecha = jPromociones.getJSONObject(i).getString("days");	
						objPromocion.setStrDias(strFecha);
						
						objPromocion.setFltDescuento((float)jPromociones.getJSONObject(i).getDouble("discount"));
						lstPromociones.add(objPromocion);
					} catch (JSONException e) {
						e.printStackTrace();
					} catch (ParseException e) {
						e.printStackTrace();
					}
				}			
			}
			
			Log.e("date",(new Date()).toString());
	        List<PromocionBean> lstPromocionAux=new ArrayList<PromocionBean>();
	
	        for (int i=0;i<lstPromociones.size();i++){
	            Date dteFecFin= new Date(lstPromociones.get(i).getDteFechaFin().getTime());
	            dteFecFin.setHours(23);
	            dteFecFin.setMinutes(59);
	            dteFecFin.setSeconds(59);
				if ((((new Date()).getTime())<=dteFecFin.getTime()) && ((new Date()).getTime()>=lstPromociones.get(i).getDteFechaInicio().getTime())){
					
					String strDias= lstPromociones.get(i).getStrDias();
					int a =((new Date()).getDay()+7-1)%7; //uso esto porque en BD se guardan los dias desde lunes y en java se empieza desde domingo
					strDias=strDias.substring(a,a+1);
					
					if (strDias.compareTo("1")==0)							
						lstPromocionAux.add(lstPromociones.get(i));
				}
			}
	        
	        if (lstPromocionAux.size()==0){
	        	Spinner cboPromocion= (Spinner) findViewById(R.id.VentaCboPromocion);
		        ArrayAdapter cboAdapterHorario = new ArrayAdapter(me,android.R.layout.simple_spinner_item, new String[] {   
		                      "Ninguno"});
		        cboAdapterHorario.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		        cboPromocion.setAdapter(cboAdapterHorario);
	        } 
	        else{
	        	Spinner cboPromocion= (Spinner) findViewById(R.id.VentaCboPromocion);
		        ArrayAdapter<PromocionBean> cboAdapterPromo = new ArrayAdapter(me,android.R.layout.simple_spinner_item,lstPromocionAux);
		        cboAdapterPromo.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		        cboPromocion.setAdapter(cboAdapterPromo);
	        	
	        }
    	}else{
    		
    		Toast.makeText(this,"Problema de conexion", Toast.LENGTH_SHORT).show();
    	}
        /*
		
		
		 //LLenar spinner
		Spinner cboPromocion= (Spinner) findViewById(R.id.VentaCboPromocion);
        ArrayAdapter cboAdapterPromocion = new ArrayAdapter(this,android.R.layout.simple_spinner_item, new String[] {   
                      "Ninguno"});
        cboAdapterPromocion.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        cboPromocion.setAdapter(cboAdapterPromocion);
        */
    }
    public void cargarCboZonas(){
    	//*carga spineer con zona
		Spinner cboZona= (Spinner) findViewById(R.id.VentaCboZona);
        ArrayAdapter<ZonaBean> spinner_adapter = new ArrayAdapter<ZonaBean> (me, android.R.layout.simple_spinner_item,lstZonas);
        spinner_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        cboZona.setAdapter(spinner_adapter);
    	
    }
    
    public void llenarZonas(){
    	if (isNetworkAvailable()==true){
			JSONArray jZonas;
			try {
				JSONReader reader = new JSONReader();
				reader.setJSONReaderListener((JSONReaderListener)this);
				//jZonas=(reader.execute("http://200.16.7.112:3000/sales_management/sales_points/dameZonas/1.json")).get();
				jZonas=(reader.execute("http://200.16.7.112:3000/sales_management/sales_points/dameZonas/"+objEvento.getIdEvento()+".json")).get();
			} catch (InterruptedException e1) {
				e1.printStackTrace();
				return;
			} catch (ExecutionException e1) {
				e1.printStackTrace();
				return;
			}		
			if (jZonas!=null){    		
				lstZonas.clear();
				
				ZonaBean objZona= new ZonaBean();
				objZona.setStrNombre("Ninguna");
				objZona.setFltTarifa(0);
				lstZonas.add(objZona);
				
				for(int i=0;i<jZonas.length();i++){
					objZona= new ZonaBean();
					
					try {
						objZona.setIntId(jZonas.getJSONObject(i).getJSONObject("zone").getInt("id"));
						objZona.setStrNombre(jZonas.getJSONObject(i).getJSONObject("zone").getString("nombre"));
						objZona.setStrDescripcion(jZonas.getJSONObject(i).getJSONObject("zone").getString("descripcion"));
						objZona.setFltTarifa((float)jZonas.getJSONObject(i).getJSONObject("zone").getDouble("fare"));
					} catch (JSONException e) {
						e.printStackTrace();
					}
					lstZonas.add(objZona);
				}
			}
			else{   		
	    	}
			Spinner cboZona= (Spinner) findViewById(R.id.VentaCboZona);
			
			List<ZonaBean> lstZonas= new ArrayList<ZonaBean>();
			ZonaBean objZona= new ZonaBean();
			objZona.setStrNombre("Ninguna");
			objZona.setFltTarifa(0);
			lstZonas.add(objZona);
	        ArrayAdapter<ZonaBean> cboAdapterZona= new ArrayAdapter<ZonaBean>(this,android.R.layout.simple_spinner_item,lstZonas);
	        cboAdapterZona.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
	        cboZona.setAdapter(cboAdapterZona);		
    	}else{
    		
    		Toast.makeText(this,"Problema de conexion", Toast.LENGTH_SHORT).show();
    	}

    }
    public void llenarHorarios(){
    	if (isNetworkAvailable()==true){
	        JSONArray jHorarios;
			try {
				JSONReader reader = new JSONReader();
				reader.setJSONReaderListener((JSONReaderListener)this);
				//jHorarios=(reader.execute("http://200.16.7.112:3000/sales_management/sales_points/dameHorariosEvento/1.json")).get();
				jHorarios=(reader.execute("http://200.16.7.112:3000/sales_management/sales_points/dameHorariosEvento/"+objEvento.getIdEvento()+".json")).get();
			} catch (InterruptedException e1) {
				e1.printStackTrace();
				return;
			} catch (ExecutionException e1) {
				e1.printStackTrace();
				return;
			}		
			if (jHorarios!=null){   
				lstHorarios.clear();
				
				for(int i=0;i<jHorarios.length();i++){
					
					HorarioBean objHorario = new HorarioBean();
					
					try {
						objHorario.setIntId(jHorarios.getJSONObject(i).getJSONObject("event_schedule").getInt("id"));
						
						String strFecha;
						strFecha = jHorarios.getJSONObject(i).getJSONObject("event_schedule").getString("fecha");
						String[] arrAux=strFecha.split("-");
						objHorario.setDteFecha(new Date(Integer.parseInt(arrAux[0])-1900,Integer.parseInt(arrAux[1])-1,Integer.parseInt(arrAux[2])));
	
						SimpleDateFormat formatoDelTexto=new SimpleDateFormat("HH:mm:ss");
	
						strFecha = ((jHorarios.getJSONObject(i).getJSONObject("event_schedule").getString("hora_inicio").split("T")[1]).split("Z"))[0];					
						objHorario.setDteHoraInicio(formatoDelTexto.parse(strFecha));
	
	
						strFecha = ((jHorarios.getJSONObject(i).getJSONObject("event_schedule").getString("hora_fin").split("T")[1]).split("Z"))[0];
						objHorario.setDteHoraFin(formatoDelTexto.parse(strFecha));
						
					} catch (JSONException e) {
						e.printStackTrace();
					} catch (ParseException e) {
						e.printStackTrace();
					}
					
					lstHorarios.add(objHorario);
				}
	    	}
	    	else{
	   		
	    	}
			
			
			List<HorarioBean> lstHoraAux= new ArrayList<HorarioBean>();
			HorarioBean objHora=new HorarioBean();
			objHora.setStrDia("Ninguno");
			lstHoraAux.add(objHora);
			Spinner cboHorario= (Spinner) findViewById(R.id.VentaCboHorario);
	        ArrayAdapter<HorarioBean> spinner_adapter = new ArrayAdapter<HorarioBean> (me, android.R.layout.simple_spinner_item,lstHoraAux);
	        spinner_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
	        cboHorario.setAdapter(spinner_adapter);
    	}else{
    		Toast.makeText(this,"Problema de conexion", Toast.LENGTH_SHORT).show();
    	}
		
		//LLenar spinner
        /*
        Spinner cboHorario= (Spinner) findViewById(R.id.VentaCboHorario);
        ArrayAdapter cboAdapterHorario = new ArrayAdapter(this,android.R.layout.simple_spinner_item, new String[] {   
                      "Ninguno"});
        cboAdapterHorario.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        cboHorario.setAdapter(cboAdapterHorario);
        */
    }
    
    public void onContinuarClick (View botton){
    	//Intent intent= new Intent();
    	//intent.setClass(this, Pagos.class);
    	//startActivity(intent);
    	//((Principal)this.getParent()).setVenta(this.venta);
    	TabActivity padre=(TabActivity)getParent();
		padre.getTabHost().setCurrentTab(2);
		
		//Pagos auxi=padre.getTabHost().getChildAt(1);
    	
    	
    }
    public void onCancelarClick (View botton){    	
    	
    	((Principal)this.getParent()).setVenta(null);
    	
    	TabActivity padre=(TabActivity)getParent();
		padre.getTabHost().setCurrentTab(0);		
    	
    }
    public void onAgregarClick (View botton){
    	
    	Spinner cboHorario= (Spinner) findViewById(R.id.VentaCboHorario);
    	try {
    		if (((String)cboHorario.getSelectedItem()).compareTo("Ninguno")==0){
        		Toast.makeText(this, "Tiene que seleccionar un horario", Toast.LENGTH_LONG).show();	
        		return;
        	}
		} catch (Exception e) {
			// TODO: handle exception
		}
    	
    	TextView txtPrecio=(TextView) findViewById(R.id.VentaTxtPrecio);
    	try {
    		Float.parseFloat(txtPrecio.getText().toString());
		} catch (Exception e) {
			// TODO: handle exception
			Toast.makeText(this, "Tiene que seleccionar una zona", Toast.LENGTH_LONG).show();	
    		return;
		}
    	
    	TextView txtAsiento=(TextView) findViewById(R.id.VentaTxtAsiento);
    	try {
    		if (txtAsiento.getText().toString().compareTo("-")!=0)
    			Integer.parseInt(txtAsiento.getText().toString());
		} catch (Exception e) {
			// TODO: handle exception
			Toast.makeText(this, "Tiene que seleccionar un asiento", Toast.LENGTH_LONG).show();	
    		return;
		}
    	
    	int contAux=intAsientosDisponibles-1;
    	for (int i=0;i<lstEntrada.size();i++){
    		if (lstEntrada.get(i).getStrNombreEvento().compareTo(objEvento.getStrNombre())==0)
    			if (lstEntrada.get(i).getObjZona().getIntId()==((ZonaBean)((Spinner)findViewById(R.id.VentaCboZona)).getSelectedItem()).getIntId())
		    		if (lstEntrada.get(i).getDteDia().getTime()==dteCurrent.getTime())
		    			if (lstEntrada.get(i).getDteHoraInicio().getTime()==((HorarioBean)cboHorario.getSelectedItem()).getDteHoraInicio().getTime())
		    				if ((""+lstEntrada.get(i).getIntAsiento()).compareTo(txtAsiento.getText().toString())==0){
		    					Toast.makeText(this, "Este asiento en este horario ya ha sido seleccionado", Toast.LENGTH_LONG).show();	;
		    					return;
		    				}
		    				else if(txtAsiento.getText().toString().compareTo("-")==0){
		    					if (contAux==0){
		    						Toast.makeText(this, "Se supero el maximo de asientos disponibles en esta zona", Toast.LENGTH_LONG).show();
			    					return;
		    					}
		    					contAux--;
		    				}
    	}
    	
    	
    	EntradaBean objEntrada=new EntradaBean();
    	
    	objEntrada.setStrNombreEvento(objEvento.getStrNombre());
    	
    	
    	objEntrada.setDteDia(dteCurrent);
    	
    	
    	txtPrecio=(TextView) findViewById(R.id.VentaTxtPrecio);
    	objEntrada.setFltTarifa(Float.parseFloat(txtPrecio.getText().toString()));
    	venta.setMontototal(venta.getMontototal()+objEntrada.getFltTarifa());
    	
    	txtAsiento=(TextView) findViewById(R.id.VentaTxtAsiento);
    	if (txtAsiento.getText().toString().compareTo("-")==0){
    		objEntrada.setIntAsiento(0);
    	}else
    		objEntrada.setIntAsiento(Integer.parseInt(txtAsiento.getText().toString()));
    	
    	Spinner cboPromocion= (Spinner) findViewById(R.id.VentaCboPromocion);
    	if (cboPromocion.getSelectedItem() instanceof PromocionBean){
    		objEntrada.setObjPromocion((PromocionBean)cboPromocion.getSelectedItem());
    	}
    	
    	cboHorario= (Spinner) findViewById(R.id.VentaCboHorario);
    	objEntrada.setDteHoraInicio(((HorarioBean)cboHorario.getSelectedItem()).getDteHoraInicio());
    	objEntrada.setIdHorario(((HorarioBean)cboHorario.getSelectedItem()).getIntId());
    	
    	objEntrada.setIdEvento(this.objEvento.getIdEvento());
    	
    	Spinner cboZona= (Spinner) findViewById(R.id.VentaCboZona);
    	objEntrada.setObjZona((ZonaBean)cboZona.getSelectedItem());
    	
    	
    	lstEntrada.add(objEntrada);
    	
    	//DetallePago objDetallePago= new DetallePago();
		//falta hacer el set
		//lstDetallePago.add(objDetallePago);
		//aca voy a probar mandar datos entre activitidades
				///BLA BLA BLA BLA
				//BLA BLA BLAA BLA
				//BLA BLA BLA BLA
				//BLA BLA BLA BLA
				//EditText dato= (EditText) findViewById(R.id.venta_datoPrueba);
		//AHHH POR CIERTO FAVOR DE ESTANDARIZAR LOS IDS DE LOS ELEMENTOS QUE UTILICEN YA QUE
		//EL ID DE ESTE EDITBOX SE REPETIA Y NO ME DEJABA CAPTAR BIEN EL DATO Y PERDI TIEMPO
		//POR LAS PURAS
			//	EditText dato= (EditText) findViewById(R.id.VentaTxtAsiento);
			//	ManejadorEntradas answer = ManejadorEntradas.getInstance();
			//	PruebaDatos auxiliar=new PruebaDatos();
			//	String asasas=dato.getText().toString();
			//	auxiliar.setNombre(asasas);
			//	answer.setNamet(asasas);
				
			//	answer.setRequest(auxiliar);
				//ACA TERMINA LO QUE ESTOY PROVANDOOOO
				//BLA BLA BLA BLA
				//BLA BLA BLA BLA
				//BLA BLA BLA BLA
		loadTableLayout();		
    }
    
	public void loadTableLayout(){
			
		tbllDetalle.removeAllViews();
		for (int intContador=0;intContador<lstEntrada.size();intContador++){
			TableRow tblrDetallePago = new TableRow(this);			
			tblrDetallePago.setLayoutParams(new LayoutParams(android.view.ViewGroup.LayoutParams.MATCH_PARENT,android.view.ViewGroup.LayoutParams.WRAP_CONTENT));
			
			TextView txtEvento = new TextView(this);
			txtEvento.setText(lstEntrada.get(intContador).getStrNombreEvento());
			txtEvento.setLayoutParams(new LayoutParams(((TextView) findViewById(R.id.VentaCol1)).getWidth(),android.view.ViewGroup.LayoutParams.WRAP_CONTENT));
			txtEvento.setGravity(Gravity.CENTER);
			tblrDetallePago.addView(txtEvento);
			
			TextView txtFecha = new TextView(this);
			Date dteEvento= lstEntrada.get(intContador).getDteDia();
			txtFecha.setText(dteEvento.getDate()+"/"+(dteEvento.getMonth()+1)+"/"+(dteEvento.getYear()+1900));
			txtFecha.setLayoutParams(new LayoutParams(((TextView) findViewById(R.id.VentaCol2)).getWidth(),android.view.ViewGroup.LayoutParams.WRAP_CONTENT));
			txtFecha.setGravity(Gravity.CENTER);
			tblrDetallePago.addView(txtFecha);			
			
			TextView txtHorario = new TextView(this);
			SimpleDateFormat format=new SimpleDateFormat("HH:mm");			
			txtHorario.setText(format.format(lstEntrada.get(intContador).getDteHoraInicio()));
			txtHorario.setLayoutParams(new LayoutParams(((TextView) findViewById(R.id.VentaCol3)).getWidth(),android.view.ViewGroup.LayoutParams.WRAP_CONTENT));
			txtHorario.setGravity(Gravity.CENTER);
			tblrDetallePago.addView(txtHorario);
			
			TextView txtZona = new TextView(this);
			txtZona.setText(lstEntrada.get(intContador).getObjZona().getStrNombre());
			txtZona.setLayoutParams(new LayoutParams(((TextView) findViewById(R.id.VentaCol4)).getWidth(),android.view.ViewGroup.LayoutParams.WRAP_CONTENT));
			txtZona.setGravity(Gravity.CENTER);
			tblrDetallePago.addView(txtZona);
			
			TextView txtAsiento = new TextView(this);
			txtAsiento.setText(""+((lstEntrada.get(intContador).getIntAsiento()==0)?"-":lstEntrada.get(intContador).getIntAsiento()));
			txtAsiento.setLayoutParams(new LayoutParams(((TextView) findViewById(R.id.VentaCol5)).getWidth(),android.view.ViewGroup.LayoutParams.WRAP_CONTENT));
			txtAsiento.setGravity(Gravity.CENTER);
			tblrDetallePago.addView(txtAsiento);
			
			TextView txtPrecio = new TextView(this);
			txtPrecio.setText(""+lstEntrada.get(intContador).getFltTarifa());
			txtPrecio.setLayoutParams(new LayoutParams(((TextView) findViewById(R.id.VentaCol6)).getWidth(),android.view.ViewGroup.LayoutParams.WRAP_CONTENT));
			txtPrecio.setGravity(Gravity.CENTER);
			tblrDetallePago.addView(txtPrecio);
			
			Button btnEliminar=new Button(this);
			btnEliminar.setId(intContador);
			btnEliminar.setText("Eliminar");
			btnEliminar.setLayoutParams(new LayoutParams(((TextView) findViewById(R.id.VentaCol7)).getWidth(),android.view.ViewGroup.LayoutParams.WRAP_CONTENT));
			btnEliminar.setOnClickListener(this);
			tblrDetallePago.addView(btnEliminar);
			
			tbllDetalle.addView(tblrDetallePago);
			
			
		}		
		//http://www.warriorpoint.com/blog/2009/07/01/android-creating-tablerow-rows-inside-a-tablelayout-programatically/
	}
	private int dp( final float value ) {
        final float density = getResources().getDisplayMetrics().density;
        return Math.round( value * density );
    }
	@Override
	public void onSelectedDayChange(CalendarView arg0, int arg1, int arg2,
			int arg3) {
		//Toast.makeText(this, ""+(new Date(arg0.getDate())), Toast.LENGTH_LONG).show();
	}
	@Override
	public void onClick(View v) {

		if (v == prevMonth)
		{
			dteCurrent=null;
			btnPreviousButtonCalendar=null;
			//lstHorarios.clear();
			if (month <= 1)
				{
					month = 12;
					year--;
				}
			else
				{
					month--;
				}
			
			List<HorarioBean> lstHoraAux= new ArrayList<HorarioBean>();
			HorarioBean objHora=new HorarioBean();
			objHora.setStrDia("Ninguno");
			lstHoraAux.add(objHora);
			Spinner cboHorario= (Spinner) findViewById(R.id.VentaCboHorario);
	        ArrayAdapter<HorarioBean> spinner_adapter = new ArrayAdapter<HorarioBean> (me, android.R.layout.simple_spinner_item,lstHoraAux);
	        spinner_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
	        cboHorario.setAdapter(spinner_adapter);
			/*
			Spinner cboHorario= (Spinner) findViewById(R.id.VentaCboHorario);
	        ArrayAdapter cboAdapterHorario = new ArrayAdapter(this,android.R.layout.simple_spinner_item, new String[] {   
	                      "Ninguno"});
	        cboAdapterHorario.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
	        cboHorario.setAdapter(cboAdapterHorario);
	        */
			
	        Spinner cboZona= (Spinner) findViewById(R.id.VentaCboZona);
			
			List<ZonaBean> lstZonas= new ArrayList<ZonaBean>();
			ZonaBean objZona= new ZonaBean();
			objZona.setStrNombre("Ninguna");
			objZona.setFltTarifa(0);
			lstZonas.add(objZona);
	        ArrayAdapter<ZonaBean> cboAdapterZona= new ArrayAdapter<ZonaBean>(this,android.R.layout.simple_spinner_item,lstZonas);
	        cboAdapterZona.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
	        cboZona.setAdapter(cboAdapterZona);
	        
			setGridCellAdapterToDate(month, year);
			
			
		}
		else if (v == nextMonth)
		{
			dteCurrent=null;
			btnPreviousButtonCalendar=null;
			//lstHorarios.clear();
			if (month > 11)
				{
					month = 1;
					year++;
				}
			else
				{
					month++;
				}
			/*
			Spinner cboHorario= (Spinner) findViewById(R.id.VentaCboHorario);
	        ArrayAdapter cboAdapterHorario = new ArrayAdapter(this,android.R.layout.simple_spinner_item, new String[] {   
	                      "Ninguno"});
	        cboAdapterHorario.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
	        cboHorario.setAdapter(cboAdapterHorario);
	        */
			List<HorarioBean> lstHoraAux= new ArrayList<HorarioBean>();
			HorarioBean objHora=new HorarioBean();
			objHora.setStrDia("Ninguno");
			lstHoraAux.add(objHora);
			Spinner cboHorario= (Spinner) findViewById(R.id.VentaCboHorario);
	        ArrayAdapter<HorarioBean> spinner_adapter = new ArrayAdapter<HorarioBean> (me, android.R.layout.simple_spinner_item,lstHoraAux);
	        spinner_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
	        cboHorario.setAdapter(spinner_adapter);
	        
	        Spinner cboZona= (Spinner) findViewById(R.id.VentaCboZona);
			
			List<ZonaBean> lstZonas= new ArrayList<ZonaBean>();
			ZonaBean objZona= new ZonaBean();
			objZona.setStrNombre("Ninguna");
			objZona.setFltTarifa(0);
			lstZonas.add(objZona);
	        ArrayAdapter<ZonaBean> cboAdapterZona= new ArrayAdapter<ZonaBean>(this,android.R.layout.simple_spinner_item,lstZonas);
	        cboAdapterZona.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
	        cboZona.setAdapter(cboAdapterZona);		
	        
			setGridCellAdapterToDate(month, year);
			
			
		}
		else if (v instanceof Button){
			
			venta.setMontototal(venta.getMontototal()-lstEntrada.get(v.getId()).getFltTarifa());
			lstEntrada.remove(v.getId());
			
			loadTableLayout();				
		}
		else{
			TextView txtAsiento=(TextView) findViewById(R.id.VentaTxtAsiento);
	    	txtAsiento.setText(((TextView)v).getText().toString());
		}
	}
	@Override
	public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		
		if (arg0.getId()==R.id.VentaCboHorario){
			Spinner auxSpinner=(Spinner)arg0;			
			
			if (((HorarioBean)auxSpinner.getSelectedItem()).getStrDia().compareTo("Ninguno")==0){
				
				Spinner cboZona= (Spinner) findViewById(R.id.VentaCboZona);
				
				List<ZonaBean> lstZonas= new ArrayList<ZonaBean>();
				ZonaBean objZona= new ZonaBean();
				objZona.setStrNombre("Ninguna");
				objZona.setFltTarifa(0);
				lstZonas.add(objZona);
		        ArrayAdapter<ZonaBean> cboAdapterZona= new ArrayAdapter<ZonaBean>(this,android.R.layout.simple_spinner_item,lstZonas);
		        cboAdapterZona.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		        cboZona.setAdapter(cboAdapterZona);					
			}
			else{
				cargarCboZonas();				
			}
			
	        
	        if (((ZonaBean)((Spinner)findViewById(R.id.VentaCboZona)).getSelectedItem()).getStrNombre().compareTo("Ninguna")==0)
				cargarZonas();
			else
				cargarUbicaciones();
		}
		else if (arg0.getId()==R.id.VentaCboZona){		
			float fltDescuento=1;
			Spinner cboPromocion= (Spinner) findViewById(R.id.VentaCboPromocion);
			if (!(cboPromocion.getSelectedItem() instanceof String)){
				PromocionBean objPromoAux=(PromocionBean)cboPromocion.getSelectedItem();
				fltDescuento=(100-objPromoAux.getFltDescuento())/100;
			}
			
			EditText txtAsiento=(EditText) findViewById(R.id.VentaTxtAsiento);
			txtAsiento.setText("");
			
			EditText txtPrecio=(EditText) findViewById(R.id.VentaTxtPrecio);
			float fltTarifaAux=lstZonas.get(arg2).getFltTarifa()*fltDescuento;
			
			if (fltTarifaAux==0)
				txtPrecio.setText("");
			else{
				DecimalFormat df = new DecimalFormat("#.##");
				txtPrecio.setText(""+df.format(fltTarifaAux));
				txtPrecio.setText(txtPrecio.getText().toString().replace(',', '.'));
			}
			
			if (((ZonaBean)((Spinner)arg0).getSelectedItem()).getStrNombre().compareTo("Ninguna")==0)
				cargarZonas();
			else
				cargarUbicaciones();
			
		}
		else if (arg0.getId()==R.id.VentaCboPromocion){
			if (((ZonaBean)((Spinner)findViewById(R.id.VentaCboZona)).getSelectedItem()).getStrNombre().compareTo("Ninguna")!=0){
				Spinner auxSpinner=(Spinner)arg0;	
				float fltDescuento=1;
				if (!(auxSpinner.getSelectedItem() instanceof String)){
					PromocionBean objPromoAux=(PromocionBean)auxSpinner.getSelectedItem();
					EditText txtPrecio=(EditText) findViewById(R.id.VentaTxtPrecio);
					fltDescuento=(100-objPromoAux.getFltDescuento())/100;
					
					float fltTarifaAux=((ZonaBean)((Spinner)findViewById(R.id.VentaCboZona)).getSelectedItem()).getFltTarifa()*fltDescuento;
					DecimalFormat df = new DecimalFormat("#.##");
					txtPrecio.setText(""+df.format(fltTarifaAux));
					txtPrecio.setText(txtPrecio.getText().toString().replace(',', '.'));
				}
				else{
					EditText txtPrecio=(EditText) findViewById(R.id.VentaTxtPrecio);
					float fltTarifaAux=((ZonaBean)((Spinner)findViewById(R.id.VentaCboZona)).getSelectedItem()).getFltTarifa()*fltDescuento;
					
					if (fltTarifaAux==0)
						txtPrecio.setText("");
					else{
						DecimalFormat df = new DecimalFormat("#.##");
						txtPrecio.setText(""+df.format(fltTarifaAux));
						txtPrecio.setText(txtPrecio.getText().toString().replace(',', '.'));						
					}
				}					
			}			
		}
	}
	@Override
	public void onNothingSelected(AdapterView<?> arg0) {
		// TODO Auto-generated method stub
		
	}
	
	
	
	private void setGridCellAdapterToDate(int month, int year)
	{
		adapter = new GridCellAdapter(getApplicationContext(), R.id.calendar_day_gridcell, month, year);
		_calendar.set(year, month - 1, _calendar.get(Calendar.DAY_OF_MONTH));
		currentMonth.setText(dateFormatter.format(dateTemplate, _calendar.getTime()));
		adapter.notifyDataSetChanged();
		calendarView.setAdapter(adapter);
	}	
	public class GridCellAdapter extends BaseAdapter implements OnClickListener
	{
		private static final String tag = "GridCellAdapter";
		private final Context _context;

		private final List<String> list;
		private static final int DAY_OFFSET = 1;
		private final String[] weekdays = new String[]{"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};
		private final String[] months = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};
		private final int[] daysOfMonth = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
		private final int month, year;
		private int daysInMonth, prevMonthDays;
		private int currentDayOfMonth;
		private int currentWeekDay;
		private Button gridcell;
		private TextView num_events_per_day;
		private final HashMap eventsPerMonthMap;
		private final SimpleDateFormat dateFormatter = new SimpleDateFormat("dd-MMM-yyyy");

		// Days in Current Month
		public GridCellAdapter(Context context, int textViewResourceId, int month, int year)
			{
				super();
				this._context = context;
				this.list = new ArrayList<String>();
				this.month = month;
				this.year = year;

				Calendar calendar = Calendar.getInstance();
				setCurrentDayOfMonth(calendar.get(Calendar.DAY_OF_MONTH));
				setCurrentWeekDay(calendar.get(Calendar.DAY_OF_WEEK));

				// Print Month
				printMonth(month, year);

				// Find Number of Events
				eventsPerMonthMap = findNumberOfEventsPerMonth(year, month);
			}
		private String getMonthAsString(int i)
			{
				return months[i];
			}

		private String getWeekDayAsString(int i)
			{
				return weekdays[i];
			}

		private int getNumberOfDaysOfMonth(int i)
			{
				return daysOfMonth[i];
			}

		public String getItem(int position)
			{
				return list.get(position);
			}

		@Override
		public int getCount()
			{
				return list.size();
			}

		/**
		 * Prints Month
		 * 
		 * @param mm
		 * @param yy
		 */
		private void printMonth(int mm, int yy)
			{
				// The number of days to leave blank at
				// the start of this month.
				int trailingSpaces = 0;
				int leadSpaces = 0;
				int daysInPrevMonth = 0;
				int prevMonth = 0;
				int prevYear = 0;
				int nextMonth = 0;
				int nextYear = 0;

				int currentMonth = mm - 1;
				String currentMonthName = getMonthAsString(currentMonth);
				daysInMonth = getNumberOfDaysOfMonth(currentMonth);

				// Gregorian Calendar : MINUS 1, set to FIRST OF MONTH
				GregorianCalendar cal = new GregorianCalendar(yy, currentMonth, 1);

				if (currentMonth == 11)
					{
						prevMonth = currentMonth - 1;
						daysInPrevMonth = getNumberOfDaysOfMonth(prevMonth);
						nextMonth = 0;
						prevYear = yy;
						nextYear = yy + 1;
					}
				else if (currentMonth == 0)
					{
						prevMonth = 11;
						prevYear = yy - 1;
						nextYear = yy;
						daysInPrevMonth = getNumberOfDaysOfMonth(prevMonth);
						nextMonth = 1;
					}
				else
					{
						prevMonth = currentMonth - 1;
						nextMonth = currentMonth + 1;
						nextYear = yy;
						prevYear = yy;
						daysInPrevMonth = getNumberOfDaysOfMonth(prevMonth);
					}

				// Compute how much to leave before before the first day of the
				// month.
				// getDay() returns 0 for Sunday.
				int currentWeekDay = cal.get(Calendar.DAY_OF_WEEK) - 1;
				trailingSpaces = currentWeekDay;


				if (cal.isLeapYear(cal.get(Calendar.YEAR)) && mm == 1)
					{
						++daysInMonth;
					}

				// Trailing Month days
				for (int i = 0; i < trailingSpaces; i++)
					{
						list.add(String.valueOf((daysInPrevMonth - trailingSpaces + DAY_OFFSET) + i) + "-GREY" + "-" + prevMonth + "-" + prevYear);
					}

				

				// Current Month Days
				for (int i = 1; i <= daysInMonth; i++)
					{
						boolean blnEntro=false;
						List<HorarioBean> lstAux= new ArrayList<HorarioBean>();
						for (int j=0;j<lstHorarios.size();j++){
							if(lstHorarios.get(j).getDteFecha().getMonth()==currentMonth)
								if (lstHorarios.get(j).getDteFecha().getDate()==i){
									list.add(String.valueOf(i) + "-YELLOW" + "-" + currentMonth + "-" + yy);
									blnEntro=true;
									break;
								}
						}
						if (blnEntro==false)
							list.add(String.valueOf(i) + "-WHITE" + "-" + currentMonth + "-" + yy);
					
					
					
						/*
						if (i == getCurrentDayOfMonth())
							{
								list.add(String.valueOf(i) + "-YELLOW" + "-" + currentMonth + "-" + yy);
							}
						else
							{
								list.add(String.valueOf(i) + "-WHITE" + "-" + currentMonth + "-" + yy);
							}^
						*/
					}

				// Leading Month days
				for (int i = 0; i < list.size() % 7; i++)
					{
						list.add(String.valueOf(i + 1) + "-GREY" + "-" + nextMonth + "-" + nextYear);
					}
			}

		/**
		 * NOTE: YOU NEED TO IMPLEMENT THIS PART Given the YEAR, MONTH, retrieve
		 * ALL entries from a SQLite database for that month. Iterate over the
		 * List of All entries, and get the dateCreated, which is converted into
		 * day.
		 * 
		 * @param year
		 * @param month
		 * @return
		 */
		private HashMap findNumberOfEventsPerMonth(int year, int month)
			{
				HashMap map = new HashMap<String, Integer>();
				// DateFormat dateFormatter2 = new DateFormat();
				//						
				// String day = dateFormatter2.format("dd", dateCreated).toString();
				//
				// if (map.containsKey(day))
				// {
				// Integer val = (Integer) map.get(day) + 1;
				// map.put(day, val);
				// }
				// else
				// {
				// map.put(day, 1);
				// }
				return map;
			}

		@Override
		public long getItemId(int position)
			{
				return position;
			}

		@Override
		public View getView(int position, View convertView, ViewGroup parent)
			{
				View row = convertView;
				if (row == null)
					{
						LayoutInflater inflater = (LayoutInflater) _context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
						row = inflater.inflate(R.layout.calendar_day_gridcell, parent, false);
					}

				// Get a reference to the Day gridcell
				gridcell = (Button) row.findViewById(R.id.calendar_day_gridcell);
				gridcell.setOnClickListener(this);

				// ACCOUNT FOR SPACING

				String[] day_color = list.get(position).split("-");
				String theday = day_color[0];
				String themonth = day_color[2];
				String theyear = day_color[3];
				if ((!eventsPerMonthMap.isEmpty()) && (eventsPerMonthMap != null))
					{
						if (eventsPerMonthMap.containsKey(theday))
							{
								num_events_per_day = (TextView) row.findViewById(R.id.num_events_per_day);
								Integer numEvents = (Integer) eventsPerMonthMap.get(theday);
								num_events_per_day.setText(numEvents.toString());
							}
					}

				// Set the Day GridCell
				gridcell.setText(theday);
				gridcell.setTag(theday + "-" + themonth + "-" + theyear);

				if (day_color[1].equals("GREY"))
					{
						gridcell.setTextColor(Color.LTGRAY);
						gridcell.setEnabled(false);
					}
				if (day_color[1].equals("WHITE"))
					{
						gridcell.setTextColor(Color.WHITE);
						gridcell.setEnabled(false);
					}
				if (day_color[1].equals("YELLOW"))
					{
						gridcell.setTextColor(Color.YELLOW);
					}
				if (day_color[1].equals("GREEN"))
					{
						gridcell.setTextColor(Color.GREEN);
					}
				return row;
			}
		@Override
		public void onClick(View view)
			{
				//Button aux=((Button)view);
				//if (aux.getTextColors().getDefaultColor()==Color.YELLOW){
				if (btnPreviousButtonCalendar!=null)
					btnPreviousButtonCalendar.setTextColor(Color.YELLOW);
				btnPreviousButtonCalendar=((Button)view);
				btnPreviousButtonCalendar.setTextColor(Color.GREEN);
				
				String[] arrFec=((String) view.getTag()).split("-");
				dteCurrent=new Date(Integer.parseInt(arrFec[2])-1900,Integer.parseInt(arrFec[1]),Integer.parseInt(arrFec[0]));
				
				List<HorarioBean> lstHorarioAux=new ArrayList<HorarioBean>();
				
				for (int i=0;i<lstHorarios.size();i++){
					if (dteCurrent.getTime()==lstHorarios.get(i).getDteFecha().getTime()){
						HorarioBean objHorarioAux=lstHorarios.get(i);
						
						SimpleDateFormat format= new SimpleDateFormat("HH:mm");
						objHorarioAux.setStrDia(format.format(objHorarioAux.getDteHoraInicio())+" - "+format.format(objHorarioAux.getDteHoraFin()));
						lstHorarioAux.add(objHorarioAux);
						
					}
				}
				
				
				
				Spinner cboHorario= (Spinner) findViewById(R.id.VentaCboHorario);
		        ArrayAdapter<HorarioBean> spinner_adapter = new ArrayAdapter<HorarioBean> (me, android.R.layout.simple_spinner_item,lstHorarioAux);
		        spinner_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		        cboHorario.setAdapter(spinner_adapter);
		        //cboHorario.setOnItemSelectedListener(me);
					
		        me.cargarCboZonas();
			}

		public int getCurrentDayOfMonth()
			{
				return currentDayOfMonth;
			}

		private void setCurrentDayOfMonth(int currentDayOfMonth)
			{
				this.currentDayOfMonth = currentDayOfMonth;
			}
		public void setCurrentWeekDay(int currentWeekDay)
			{
				this.currentWeekDay = currentWeekDay;
			}
		public int getCurrentWeekDay()
			{
				return currentWeekDay;
			}
	}
	
	
	
	@Override
	public void onConnected() {
		// TODO Auto-generated method stub
		intContadorProgress++;
		if (intContadorProgress==1){
			myProgressDialog = ProgressDialog.show(this, "Cargando...", "Por favor esperar...", true);
			
		}
	}

	@Override
	public void onSent() {
		// TODO Auto-generated method stub
		
	}
	
	@Override
	public void onSent(List<TableRow> lstDetallePago) {
		// TODO Auto-generated method stub
		ImageView ImgEvento= (ImageView) findViewById(R.id.VentaImgEvento);
        ImgEvento.setImageDrawable(null);
        
        TableLayout tbllUbicaciones = (TableLayout) findViewById(R.id.VentaTblUbicaciones);
        tbllUbicaciones.removeAllViews();
		for (int i=0;i<lstDetallePago.size();i++)
			tbllUbicaciones.addView(lstDetallePago.get(i));
	}

	@Override
	public void onFinished(JSONArray jArray) {
		// TODO Auto-generated method stub
		intContadorProgress--;
		if (intContadorProgress==0)
			myProgressDialog.dismiss();
	}

	@Override
	public void onFinished(JSONObject jArray) {
		// TODO Auto-generated method stub
		intContadorProgress--;
		if (intContadorProgress==0)
			myProgressDialog.dismiss();
		
	}

	@Override
	public void onFinished(Integer id) {
		// TODO Auto-generated method stub
		intContadorProgress--;
		if (intContadorProgress==0)
			myProgressDialog.dismiss();		
	}
	
	private boolean isNetworkAvailable() {
        ConnectivityManager connectivityManager 
              = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo= connectivityManager.getActiveNetworkInfo();
        return activeNetworkInfo != null;
    }
}
